
const qs = require('querystring');

const path = require('path');
const fs = require('fs');
const fsp = fs.promises;


function Router(pathname, req, res) {
    if (pathname == "/data") { //   /data -> 在站点中不存在(不能作为页面展示)  ->  人为赋予/data意义 
        res.end("/data");   // 返回文本
    } else if (req.method.toLowerCase() == "get" && pathname == "/users") { //   /data -> 在站点中不存在(不能作为页面展示)  ->  人为赋予/data意义  -> 返回json数据(users.json)

        var { name = "" } = req.query;
        var msg = {};
        if (name) {
            fsp.readFile(path.join(__dirname, "../data/users.json"), "utf-8").then(txt => {
                res.writeHead(200, {
                    "Content-Type": "text/json;charset=utf-8",
                })
                var list = JSON.parse(txt);
                var findData = list.find(v => v.name == name);



                if (findData) {
                    msg.status = true;
                    msg.message = "OK";
                    msg.data = findData;

                    res.end(JSON.stringify(msg));
                } else {
                    msg.status = false;
                    msg.message = "该用户不存在";
                    res.end(JSON.stringify(msg))
                }
            })
        } else {
            fsp.readFile(path.join(__dirname, "../data/users.json"), "utf-8").then(txt => {
                res.writeHead(200, {
                    "Content-Type": "text/json;charset=utf-8",
                })

                var list = JSON.parse(txt);

                msg.status = true;
                msg.message = "OK";
                msg.data = list;

                res.end(JSON.stringify(msg));
            })
        }

    } else if (req.method.toLowerCase() == "post" && pathname == "/users") {
        console.log("接收前端以post方式传递的数据");

        // 如何获取前端以post方式传递的数据?
        let body = "";
        req.on("data", function (chunk) { // chunk 传递的数据流(数据时文本形式)
            // console.log("chunk", chunk.toString());
            body += chunk;  // 隐式转字符串 和 拼接
        })
        req.on("end", async function () {
            console.log("body", body, typeof body);  // 主体
            console.log("content-type", req.headers['content-type']);

            // 前端传入FormData(application/x-www-form-urlencoded)=>解析参数数据队列     name=xxx&age=xxx  =>
            if (req.headers['content-type'] == "application/x-www-form-urlencoded") {
                body = qs.parse(body);  // 主体 (解析为对象)
            } else if (req.headers['content-type'] == "application/json") {
                // json字符串  application/json
                body = JSON.parse(body);
            }
            console.log(body);   //{name:"老六",age:66}




            var txt = await fsp.readFile(path.join(__dirname, "../data/users.json"));
            var list = JSON.parse(txt);

            var index = list.findIndex(v => v.name === body.name);
            var msg = {}
            if (index == -1) {  // 用户不存在  => 追加数据
                msg.status = true;
                msg.message = "用户不存在,追加数据";
                list.push(body);
            } else {
                msg.status = true;
                msg.message = "用户存在,替换数据";
                list.splice(index, 1, body);
            }

            console.log(11111111, msg);
            fsp.writeFile(path.join(__dirname, "../data/users.json"), JSON.stringify(list), { encoding: "utf-8", flag: "w" }).then(() => {
                res.end(JSON.stringify(msg))
            })


            // res.end("1111");
        })
    }
}

module.exports = Router;